package com.kitty.game.equip.handler;

import com.kitty.common.utils.ToolsPub;
import com.kitty.game.attribute.config.Attribute;
import com.kitty.game.config.Equip;
import com.kitty.game.enter.FiedValue;
import com.kitty.game.enter.RespGeneralNotify;
import com.kitty.game.equip.EquipDataPool;
import com.kitty.game.equip.model.RoleEquip;
import com.kitty.game.equip.model.RoleEquipField;
import com.kitty.game.role.model.Role;
import com.kitty.mina.message.MessagePusher;
import lombok.extern.slf4j.Slf4j;
import org.nutz.json.Json;
import org.springframework.stereotype.Component;

import java.text.MessageFormat;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Random;

import static com.kitty.game.utils.Const.MONEY_NAME;
import static com.kitty.game.utils.Const.ROLE_RESOURCE_NOT_ENOUGH;
import static com.kitty.game.utils.NotifyModules.NOTIFY_EQUIP_RESONANCE_OK;

//后加

/**
 * 共鸣属性 没有共鸣过的装备必定成功
 */
@Component("EquipResonance")
@Slf4j
public class EquipResonanceHandler extends UpgradeHandler {
    private static final List<Integer> RESONANCE = Arrays.asList(2, 5, 7, 8, 9, 12, 13, 14, 808, 50, 51, 52, 53, 54, 56, 57, 58, 59, 60, 67, 69, 77, 78, 79, 80, 85, 110, 117, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 168, 170, 171, 172, 173, 174, 225);
    private static final String PRE_MESSAGE = "你消耗了1枚#R{0}#n进行炼化属性预览。";
    private static final String SUCCESS_MESSAGE = "恭喜你，炼化成功，属性已重新生成。";
    private static final String FAIL_MESSAGE = "真遗憾，炼化失败。";
    private static final String NOT_MATCH_MESSAGE = "清放入正确的装备或材料。";
    private static final String STONE = "装备共鸣石";
    private static short FIELDID = 6914;

    /**
     * 预览炼化需要的宝石名
     */
    private String getGemName(int level) {
        if (level < 80) {
            return "蓝松石";
        } else if (level < 110) {
            return "芙蓉石";
        } else {
            return "红宝石";
        }
    }

    @Override
    public String doUpgrade(Role role, Object... params) {

        RoleEquip roleEquip = (RoleEquip) params[0];
        int size = (int) params[1];
        boolean isUseLimit = (boolean) params[2];
        Equip equip = (Equip) params[3];
        boolean success;
        /**根据道具数量判断是否成功*/
        success = isSuccess(size);
        /**判断是否第一次共鸣 如果是没有共鸣过的必定成功*/
        if (!success) {
            success = !isResonanceEquip(roleEquip);
        }

        int limitNum = 0;
        /**扣钱 扣除道具*/
        roleService.subtractMoney(role, needCash(roleEquip.queryLevel(), 0));

        limitNum += equipService.delRoloEquip(STONE, size, isUseLimit, role);
        if (isPre()) {
            limitNum += equipService.delRoloEquip(getGemName(roleEquip.queryLevel()), 1, isUseLimit, role);
        }

        if (limitNum > 0) {
            roleEquip.addLimitTime(limitNum);
        }
        if (success) {
            roleService.addAchieveScore(role,"301022");
            Random random = new Random();
            int index = random.nextInt(RESONANCE.size());
            short fiedId = RESONANCE.get(index).shortValue();
            /**删除旧的共鸣属性*/
            roleEquip.getFields().remove(getFieldId());

            Attribute attribute = attrService.getAttr(fiedId);
            short newValue=(short)(ToolsPub.getGongMingField(roleEquip.queryUpgradeLevel(), fiedId, equip.getReq_level()));
            //short newValue = Short.parseShort(strings[roleEquip.queryUpgradeLevel() - 4]);
            RoleEquipField roleEquipField = new RoleEquipField();
            roleEquipField.setType((getFieldId()));
            roleEquipField.setField(new LinkedHashMap<>());

            FiedValue fiedValue = new FiedValue(fiedId, attribute.getType(), newValue);
            log.error("共鸣属性=={}=={}",Json.toJson(fiedValue),attribute.getName());
            roleEquipField.getField().put(fiedValue.getType(), fiedValue);

            roleEquip.getFields().put(roleEquipField.getType(), roleEquipField);
            equipService.countPerfect(roleEquip);
            refreshRoleEquip(role, roleEquip);
            RespGeneralNotify respGeneralNotify = new RespGeneralNotify();
            respGeneralNotify.setValue("1");
            respGeneralNotify.setNotify((short) NOTIFY_EQUIP_RESONANCE_OK);//共鸣成功
            MessagePusher.pushMessage(role, respGeneralNotify);

            pushOperateResult(role, UPGRADE_SUCCESS);
            if (isPre()) {
                return MessageFormat.format(PRE_MESSAGE, getGemName(roleEquip.queryLevel()));
            } else {
                return SUCCESS_MESSAGE;
            }
        } else {
            pushOperateResult(role, UPGRADE_FAIL);
            return FAIL_MESSAGE;
        }
    }

    @Override
    int getNotifyType() {
        return NOTIFY_EQUIP_RESONANCE_OK;
    }

    public short getFieldId() {
        return FIELDID;
    }

    public boolean isPre() {
        return false;
    }

    /**
     * 判断物品有没有炼化过共鸣属性
     */
    public boolean isResonanceEquip(RoleEquip roleEquip) {
        return roleEquip.getFields().get((short) 6914) != null;
    }

    @Override
    public String acceptUpgrade(Role role, int upgradePos, String param) {

        RoleEquip roleEquip = equipService.getRoleEquipByPos(role, upgradePos);
        if(roleEquip==null){
            return "请放入正确的装备。";
        }
        /**使用的共鸣石数量*/
        int size = Integer.parseInt(param.split("\\|")[0]);
        /**是否使用限制道具*/
        boolean isUseLimit = param.split("\\|")[1].equals("1");
        if (!isRightPosition(roleEquip.queryEquipPos(false))) {
            return MessageFormat.format(NO_RIGHT_POSITION, "改造", roleEquip.getName());
        }
        Equip equip = EquipDataPool.getByName(roleEquip.getName());
        if (equip == null) {
            log.error("找不到装备配置ICON=[{}]", upgradePos);
            return MessageFormat.format(NOT_FIND_CONFIG, roleEquip.getName());
        }
        String content = checkResource(role, roleEquip, size, isUseLimit);
        if (content != null) {
            return content;
        }
        if (roleEquip.getType().equals("未鉴定装备")) {
            return MessageFormat.format(FAIL_MESSAGE, roleEquip.getName());
        }
        return doUpgrade(role, roleEquip, size, isUseLimit, equip);
    }


    @Override
    public String checkResource(Object... objects) {
        Role role = (Role) objects[0];
        RoleEquip roleEquip = (RoleEquip) objects[1];
        int size = (int) objects[2];
        boolean isUseLimit = (boolean) objects[3];

        if (roleEquip.queryUpgradeLevel() < 4 || !roleEquip.queryColor().equals("绿色")) {
            return NOT_MATCH_MESSAGE;
        }


        int stoneNum = equipService.getCount(STONE, isUseLimit, role);
        int gemNum = equipService.getCount(getGemName(roleEquip.queryLevel()), isUseLimit, role);

        if(size<=0){
            return ERROR_OPTYPE;
        }
        if (stoneNum < size) {
            return MessageFormat.format(ROLE_RESOURCE_NOT_ENOUGH, STONE);
        }
        if (isPre()) {
            if (gemNum < 1) {
                return MessageFormat.format(ROLE_RESOURCE_NOT_ENOUGH, getGemName(roleEquip.queryLevel()));
            }
        }

        if (role.getMoney() < needCash(roleEquip.queryLevel(), 0)) {
            return MessageFormat.format(ROLE_RESOURCE_NOT_ENOUGH, MONEY_NAME);

        }
        return null;
    }


    @Override
    public int needCash(short level, int pos) {
        return level < 70 ? 0 : level * level * 32 + 10000;
    }

    @Override
    public String getUpdateTypeStr() {
        return "equip_resonance";
    }


    /**
     * 根据放入的道具判断是否成功
     */
    private boolean isSuccess(int size) {
        Random random = new Random();
        if (size == 1) {
            int result = random.nextInt(100);
            return result < 40;// 失败
        } else if (size == 2) {
            int result = random.nextInt(100);
            return result < 70;// 失败
        }
        return true;
    }
}
